package de.bensoft.jrail.client.common;

import java.io.IOException;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.util.Callback;

import javax.inject.Inject;

import org.apache.log4j.Logger;


public class FormCreator {
	
	private static Logger LOG = Logger.getLogger(FormCreator.class);
	
	@Inject
	private Utils utils;
	
	public SceneCreatorResult createScene(Class<?> controllerClazz) {
		
		JavaFXController fxc = (JavaFXController)controllerClazz.getAnnotation(JavaFXController.class);
		
		if(fxc == null) {
			LOG.error("Cannot create Scene => " + controllerClazz.getName() + " it not annotated with JavaFXController!");
			return null;
		}
		
		String css = fxc.css();
		
		FormCreatorResult res1 = createForm(controllerClazz);
		SceneCreatorResult res2 = new SceneCreatorResult();
		res2.setController(res1.getController());
		
		Scene s = new Scene(res1.getParent());
		
		if(css.length() > 0) {
			s.getStylesheets().add(controllerClazz.getClass().getResource(css).toExternalForm());
		}
		
		res2.setScene(s);
		return res2;
	}
	
	public FormCreatorResult createForm(Class<?> controllerClazz) {
		
		if(controllerClazz == null)
			return null;
	
		JavaFXController fxc = (JavaFXController)controllerClazz.getAnnotation(JavaFXController.class);
		String fxml 		 = fxc.fxml();
		
		FXMLLoader loader = new FXMLLoader(controllerClazz.getResource(fxml));
		loader.setControllerFactory(new Callback<Class<?>,Object>() {
			public Object call(Class<?> arg0) {
				return utils.injectClass(arg0);
			}	
		});
		
		FormCreatorResult res = new FormCreatorResult();
		try {
			res.setParent((Parent)loader.load());
			res.setController(loader.getController());
		} catch (IOException e) {
			LOG.error(e);
			return null;
		}
		
		return res;
	}
	
	
}
